﻿using AutoMapper;
using MediatR;
using Traceability.API.Applications.Command.TracebackCommand;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.Applications.CommandHandler.TracebackCommandHandler
{
    public class TracebackUpdateCommandHandler : IRequestHandler<TracebackUpdateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Traceback_Information> tracebackRepository;
        private readonly IMapper mapper;


        public TracebackUpdateCommandHandler(IBaseRepository<Traceback_Information> tracebackRepository, IMapper mapper)
        {
            this.tracebackRepository = tracebackRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(TracebackUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> aPIResult = new APIResult<int>();
            
            var date = tracebackRepository.GetAll().Where(s=>!s.IsDeltede);
            if(date.Where(s=>s.Batch==request.Batch&&s.Id!=request.Id).Any())
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Msg = "批次重复";
                aPIResult.Data = 0;
                return await Task.FromResult(aPIResult);
            }

            var res = date.FirstOrDefault(s => s.Id == request.Id)!;
            res.Expiration_date = request.Expiration_date;
            res.Production_License = request.Production_License;
            res.SName = request.SName;
            res.Manufacturing_Enterprises=request.Manufacturing_Enterprises;
            res.Batch=request.Batch;
            res.UpDataTime = DateTime.Now;
            res.UpDataUserId = request.CreateUserId;
            res.Url= request.Url;

            await tracebackRepository.Update(res);


            aPIResult.Code = EnumCode.Ok;
            aPIResult.Msg = "修改成功";
            aPIResult.Data = 1;
            
            return await Task.FromResult(aPIResult);

    }
        }
}
